package com.example.controller;

import com.example.service.CompletableFutureExampleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@Slf4j
@RequestMapping("/completable/future/example")
public class CompletableFutureExampleController {

    @Autowired
    private CompletableFutureExampleService completableFutureExampleService;

    @GetMapping("/completable-future-task")
    public CompletableFuture<String> completableFutureTask() {
        return completableFutureExampleService.executeAsyncTask();
    }

    /**
     * RESTful API，触发异步任务
     *
     * @return 异步任务的结果
     */
    @GetMapping("/async-task")
    public String executeAsyncTask() {
        log.info("触发异步任务");

        CompletableFuture<String> futureResult = completableFutureExampleService.executeComplexAsyncTask();

        String result;
        try {
            // 获取异步任务的结果（阻塞等待任务完成）
            result = futureResult.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步任务执行失败", e);
            result = "异步任务失败";
        }

        log.info("异步任务结果: {}", result);
        return result;
    }
}
